﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace JTActiveSafety.Gateway.Internal
{
    public interface IServer : IDisposable
    {
        IFeatureCollection Features { get; }
        Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken) where TContext : notnull;
        Task StopAsync(CancellationToken cancellationToken);
    }
    public class KestrelServer : IServer
    {
        private KestrelServerImpl _innerKestrelServer;

        public KestrelServer(IOptions<KestrelServerOptions> options, IConnectionListenerFactory transportFactory, ILoggerFactory loggerFactory)
        {
            _innerKestrelServer = new KestrelServerImpl(
                options,
                new[] { transportFactory ?? throw new ArgumentNullException(nameof(transportFactory)) },
                loggerFactory);
        }

        public IFeatureCollection Features => _innerKestrelServer.Features;

        public KestrelServerOptions Options => _innerKestrelServer.Options;

        public Task StartAsync(IHttpApplication<TContext> application, CancellationToken cancellationToken)
        {
            return _innerKestrelServer.StartAsync(application, cancellationToken);
        }

        // Graceful shutdown if possible
        public Task StopAsync(CancellationToken cancellationToken)
        {
            return _innerKestrelServer.StopAsync(cancellationToken);
        }

        // Ungraceful shutdown
        public void Dispose()
        {
            _innerKestrelServer.Dispose();
        }
    }
}